package com.limh.readers.fragment

import android.content.Intent
import android.os.Handler
import android.support.v4.widget.SwipeRefreshLayout
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import butterknife.BindView
import com.jude.rollviewpager.RollPagerView
import com.limh.readers.R
import com.limh.readers.activity.WebInfoActivity
import com.limh.readers.adapter.RollAdapter
import com.limh.readers.bean.Article
import com.limh.readers.widget.recyclerview.adapter.CommonAdapter
import com.limh.readers.widget.recyclerview.base.ViewHolder
import com.limh.readers.widget.recyclerview.decoration.SpacesItemDecoration
import com.limh.readers.comm.Comm
import com.limh.readers.net.BaseRetrofit
import com.limh.readers.net.ServerApi
import com.limh.readers.utils.GsonUtils
import com.limh.readers.utils.LogUtil
import com.limh.readers.utils.SharePreferUtils
import com.limh.readers.utils.Utils
import com.limh.readers.widget.recyclerview.adapter.MultiItemTypeAdapter
import com.limh.readers.widget.recyclerview.wrapper.HeaderAndFooterWrapper
import com.limh.readers.widget.recyclerview.wrapper.LoadmoreWrapper
import com.squareup.picasso.Picasso
import rx.schedulers.Schedulers

/**
 * Function:每日更新
 * author: limh
 * time:2017/8/1
 */
class DayNewsFragment : BaseFragment() {
    @BindView(R.id.recy_dayupdate)
    lateinit var recyUpdate: RecyclerView
    @BindView(R.id.swipe_dayupdate)
    lateinit var swipeUpdate: SwipeRefreshLayout

    lateinit var roll: RollPagerView

    var articles: MutableList<Article>? = null
    var adapter: CommonAdapter<Article>? = null
    var loadAdapter: LoadmoreWrapper? = null
    var headerAdapter: HeaderAndFooterWrapper? = null

    var rollView: View? = null
    lateinit var topArts: MutableList<Article>
    var page = 1

    val TAG = "DayNewsFragment"

    override fun findViews(inflater: LayoutInflater?, container: ViewGroup?): View {
        return inflater?.inflate(R.layout.fragment_day_news, container, false) as View
    }

    override fun initViews() {
        articles = mutableListOf()
        topArts = mutableListOf()
        val mLayoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
        recyUpdate.layoutManager = mLayoutManager
        recyUpdate.addItemDecoration(SpacesItemDecoration(Utils.dip2px(context, 4f), Utils.dip2px(context, 10f)))

        swipeUpdate.setOnRefreshListener {
            getArticle(1)
        }
        rollView = LayoutInflater.from(context).inflate(R.layout.view_rollview_header, null)
        roll = rollView!!.findViewById(R.id.rollview)
        roll.setAnimationDurtion(500)
        roll.setPlayDelay(3000)
        roll.setOnItemClickListener { position ->
            val intent = Intent(activity, WebInfoActivity::class.java)
            intent.putExtra("id",topArts[position].id)
            intent.putExtra("title", topArts[position].artTitle)
            intent.putExtra("artLink", topArts[position].artUrl)
            intent.putExtra("author", topArts[position].artAuthor + "  " + topArts[position].time)
            intent.putExtra("table", "article")
            startActivity(intent)
        }
    }

    override fun initDatas() {
        if (topArts.size == 0) {
            getTop()
        }
        getArticle(page)
    }

    /**
     * 获取顶部推送文章
     */
    fun getTop() {
        val params = mapOf(Pair("token", Comm.TOKEN), Pair("rand","-1"))
        val service = BaseRetrofit().createService(ServerApi::class.java)
        service.getArticle(params)
                .subscribeOn(Schedulers.io())
                .subscribeOn(Schedulers.newThread())
                .subscribe({ response ->

                    when (response.getCode()) {
                        200 -> {
                            LogUtil.d(TAG, "RES=" + GsonUtils.Gson2Str(response.getData()))
                            val temp = GsonUtils.str2List(GsonUtils.Gson2Str(response.getData()), Article::class.java)
                            for (item in temp) {
                                LogUtil.d(TAG, "" + item.toString())
                            }
                            topArts.addAll(GsonUtils.str2List(GsonUtils.Gson2Str(response.getData()), Article::class.java))
                            if (topArts.size > 0)
                                sendMsg("", 0x124, handler)
                        }
                        else -> {
                            sendMsg(response.getMessage()!!, 0x125, handler)
                        }
                    }
                }, { t ->
                    LogUtil.e(TAG, t.toString())
                    sendMsg("网络异常", 0x125, handler)
                })
    }

    fun getArticle(page: Int = 1) {
        val params = mapOf(Pair("page", page.toString()), Pair("size", "10"), Pair("token", Comm.TOKEN), Pair("rand", "0"))
        val service = BaseRetrofit().createService(ServerApi::class.java)
        service.getArticle(params)
                .subscribeOn(Schedulers.io())
                .subscribeOn(Schedulers.newThread())
                .subscribe({ response ->
                    LogUtil.i(TAG, "RESULT:" + response.toString())
                    when (response.getCode()) {
                        200 -> {
                            val temp = GsonUtils.str2List(GsonUtils.Gson2Str(response.getData()), Article::class.java)
                            for (item in temp) {
                                LogUtil.d(TAG, "list=" + item.toString())
                            }
                            articles!!.addAll(temp)
                            sendMsg("", 0x123, handler)
                        }
                        else -> {
                            sendMsg(response.getMessage(), 0x125, handler)
                        }
                    }
                }, {
                    sendMsg("网络异常", 0x125, handler)
                })
    }

    private val handler = Handler(Handler.Callback { msg ->
        when (msg.what) {
            0x123 -> {
                if (null == adapter) {
                    adapter = object : CommonAdapter<Article>(context, R.layout.view_item_art_list, articles!!) {
                        override fun convert(holder: ViewHolder, t: Article, position: Int) {
                            holder.setText(R.id.txt_item_art_title, t.artTitle!!)
                            holder.setText(R.id.txt_item_art_desc, t.artDesc!!)
                            holder.setText(R.id.txt_item_art_time, (t.time + " " + t.artClass + " " + t.artAuthor))
                            //判断是否在移动网下不显示图片
                            if (SharePreferUtils.get(activity, "showImage", false) as Boolean) {
                                if (Utils.getNetworkState(activity) == Utils.NETWORK_WIFI) {
                                    try {
                                        Picasso.with(context).load(t.artPic).into(holder.getView<View>
                                        (R.id.image_item_art_pic) as ImageView)
                                    } catch (e: Exception) {
                                        holder.setVisible(R.id.image_item_art_pic, View.GONE)
                                        e.printStackTrace()
                                    }
                                } else {
                                    holder.setVisible(R.id.image_item_art_pic, View.GONE)
                                }
                            } else {
                                try {
                                    Picasso.with(context).load(t.artPic).into(holder.getView<View>
                                    (R.id.image_item_art_pic) as ImageView)
                                } catch (e: Exception) {
                                    holder.setVisible(R.id.image_item_art_pic, View.GONE)
                                    e.printStackTrace()
                                }
                            }
                        }
                    }
                    loadAdapter = LoadmoreWrapper(adapter)
                    loadAdapter!!.setLoadMoreView(R.layout.view_more)
                    loadAdapter!!.setOnLoadMoreListener {
                        LogUtil.d(TAG, "加载更多")
                        getArticle(page++)
                    }
                    headerAdapter = HeaderAndFooterWrapper(loadAdapter)
                    headerAdapter!!.addHeaderView(rollView)

                    recyUpdate.adapter = headerAdapter
                    adapter!!.setOnItemClickListener(object : MultiItemTypeAdapter.OnItemClickListener {
                        override fun onItemClick(view: View, holder: RecyclerView.ViewHolder, position: Int) {
                            val intent = Intent(activity, WebInfoActivity::class.java)
                            intent.putExtra("id",articles!![position-1].id)
                            intent.putExtra("title", articles!![position - 1].artTitle)
                            intent.putExtra("artLink", articles!![position - 1].artUrl)
                            intent.putExtra("author", articles!![position - 1].artAuthor + "  " + articles!![position - 1].time)
                            intent.putExtra("table", "article")
                            startActivity(intent)
                        }

                    })
                } else {
                    adapter!!.datas = articles!!
                    loadAdapter!!.notifyDataSetChanged()
                    headerAdapter!!.notifyDataSetChanged()
                    recyUpdate.invalidate()
                }
                for (item in articles!!)
                    LogUtil.w(TAG, "article=" + item.artTitle + " " + item.artPic)
            }
            0x124 -> {
                LogUtil.i(TAG, "显示banner")
                roll.visibility = View.VISIBLE
                roll.setAdapter(RollAdapter(context, topArts))
            }
            0x125 -> {
                showToastShort(msg.data.getString("msg"))
            }
        }
        if (swipeUpdate.isRefreshing) swipeUpdate.isRefreshing = false
        true
    })
}